<?php

namespace App\Http\Controllers\GuanyuanSSO;

use App\Http\Controllers\BaseController;
use App\Service\GuanyuanSSO\FeishuService;
use App\Service\GuanyuanSSO\GuanyuanAccountService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class LoginController extends BaseController
{
    public static function setAppId(Request $request)
    {
        $appId = $request->get("app_id");
        if ($appId) {
            FeishuService::setAppId($appId);
        }
    }

    public function index(Request $request)
    {
        self::setAppId($request);

        $url = FeishuService::makeAuthUrl();
        header("Location: {$url}");
    }

    public function login(Request $request)
    {
        self::setAppId($request);

        $this->validate($request, [
            'code' => 'required|string',
        ]);

        try {
            $arr = FeishuService::loginByCode($request->code);
        } catch (\Exception $exception) {
            Log::error(
                'GuanyuanSSO loginByCode Err:', [
                'code' => $request->code,
                'msg'  => $exception->getMessage(),
            ]
            );
            self::noPermissionTip();
            return;
//            return $this->fail(0, $exception->getMessage());
        }

        if (!isset($arr['data']['user_id'])) {
            self::noPermissionTip();
            return;
//            return $this->fail(0, '账户无权限，请联系增长研究院');
        }

        /*$userInfo = FeishuService::getUserInfoByFeishuId($arr['data']['user_id']);
        if (!isset($userInfo['code']) || $userInfo['code'] != 0) {
            return $this->fail(0, '账户无权限，请联系增长研究院');
        }

        //获取一级部门
        $departmentName = FeishuService::getDepartmentName($userInfo['data']['user']['department_ids'] ?? []);
        if ($departmentName === '') {
            $departmentInfo = FeishuService::getDepartment($userInfo['data']['user']['department_ids'][0] ?? '');
            $departmentName = $departmentInfo['data']['department']['name'] ?? '';
        }

        $guanyuanSSOUserId = FeishuService::getSSOUserId($arr['data']['user_id'], $departmentName);*/

        // 获取后台用户绑定的观远账号id
        $guanyuanSSOUserId = GuanyuanAccountService::getGuanyuanSSOUserIdByFsUserId($arr['data']['user_id']);
        if (strlen($guanyuanSSOUserId) == 0) {
            self::noPermissionTip();
            return;
//            return $this->fail(0, '账户无权限，请联系增长研究院');
        }

        // 招商只允许在公司登录
        $ip = $request->ip();
        Log::info("GuanyuanSSO.login: 观远ID: {$guanyuanSSOUserId}, 用户名: {$arr['data']['name']}, IP: {$ip}");
        /*if ($guanyuanSSOUserId == "招商") {
            if ($ip != "36.112.14.106") {
//                return $this->fail(0, '请在公司内部访问');
            }
        }*/

        $ssoUrl = FeishuService::makeGuanyuanSSOUrl($guanyuanSSOUserId);

        if (!FeishuService::isMobile()) {
            echo <<<HTML
<html>
<head>
    <meta charset="UTF-8" />
    <title>观远数据</title>
    <script>
    function openGuanyuan() {
    　　window.open ("{$ssoUrl}", "newwindow");
    }
    </script>
</head>
<body onload="openGuanyuan();" style="text-align: center;">
如果没有自动打开，请点击以下链接：<br /><br />

<a href="{$ssoUrl}" target="_blank">观远数据</a>


</body>
</html>
HTML;
            return;
        }

        return response()->redirectTo($ssoUrl);
    }

    /**
     * 观远账户无权限，请联系管理员 提示
     */
    public function noPermissionTip()
    {
        echo <<<HTML
<html>
<head>
    <meta charset="UTF-8" />
    <title>观远数据</title>
</head>
<body>

<div style="display: flex;justify-content: center;align-items: center;height: 100vh;text-align: center;font-size: 28px;">
    <p>账户无权限，<a href="https://applink.feishu.cn/T8F5WCET4hZG">请点击此处申请</a>。</p>
</div>
</body>
</html>
HTML;
    }
}
